<?php

namespace App\Http\Controllers\Api;

use  App\V3\V3_1\Models\MaterielOtherChargesModel;
use  App\V3\V3_1\Models\MaterielPayHistoryModel;
use App\Http\Controllers\Controller;
use App\Services\MaterielService;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use Validator;

class MaterielController extends BaseController
{
    /**
     * @新建采购单
     * created 在 2021/11/23 15:52 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        if(empty($request->materiel_content)) {
            return $this->fail('', '请添加需采购的物料产品');
        }

        $info = SELF::checkInput($data = $request->all());

        if($info) {
            return $info;
        }

        if(!in_array(empty($request->source)?1:$request->source, [1,2,3,4,5])) {
            return $this->fail('', '订单来源不合法，请重试');
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['purchase_no'] = SELF::createPurchaseNo();

        $this->log('新建采购单', $data);

        return response()->json(MaterielService::add($data));
    }

    /**
     * @修改采购单
     * created 在 2021/11/24 14:52 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        if(empty($request->materiel_content)) {
            return $this->fail('', '请添加需采购的物料产品');
        }

        if(empty($request->id) || !is_numeric($request->id)) {
            return $this->fail('', '参数`id`缺失');
        }

        $info = SELF::checkInput($data = $request->all());

        if($info) {
            return $info;
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        $this->log('修改采购单', $data);
        return response()->json(MaterielService::edit($data));
    }

    private function checkInput($data)
    {
        //参数验证
        $validator = Validator::make($data, [
            'supplier_customer_id' =>'required|integer',//供应商id
            'purchase_time' => 'required',//采购日期
            /* 'tax_rate' =>'required|integer|min:0',//税率 */
            // 'other_charges' => 'integer|min:0',//其他费用
            'preferential_way' => [
                'required',
                Rule::In([0, 1, 2]),
            ],//优惠方式;0:无;1:修改价格;2:折扣优惠;
            'preferential_money' =>'numeric|min:0',//优惠方式对应金额
        ]);

        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
    }

    //创建采购单号
    private function createPurchaseNo()
    {
        list($t1, $t2) = explode(' ', microtime());
        $str =(float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
        $millisecond = substr($str,10,13);
        $date = date("YmdHis").$millisecond.mt_rand(100000,999999);

        return $date;
    }

    /**
     * @修改采购单
     * created 在 2021/11/24 14:52 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('删除采购', $data);
        return response()->json(
            MaterielService::del($data)
        );
    }

    /**
     * @修改采购单
     * created 在 2021/11/25 14:09 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCharges(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'materiel_id' =>'required|integer',//销售单主键id
            'money' =>'required|string',//其他费用
            'other_type_name' =>'required|string',//其他费用类型名称
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();

        $this->log('添加采购其他费用', $data);
        return response()->json(
            MaterielService::addCharges($data)
        );
    }

    /**
     * @编辑其他费用
     * created 在 2021/11/25 14:48 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editCharges(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//其他费用主键id
            'money' =>'required|string',//其他费用
            'other_type_name' =>'string',//其他费用类型名称
            'other_remark' =>'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('添加采购其他费用', $data);
        return response()->json(
            MaterielService::editCharges($data)
        );
    }

    /**
     * @其他费用列表
     * created 在 2021/11/25 15:00 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function chargesList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'materiel_id' =>'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = MaterielOtherChargesModel::where('materiel_id',$data['materiel_id'])->get();
        return $this->success($model);
    }

    /**
     * @付款
     * created 在 2021/11/25 15:36 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function payMaterielMoney(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'materiel_id'=>'required|integer',//销售单主键
            'money'=>'required|string',//收款金额
            'pay_time'=>'required|date',//收款时间
            'payer_account'=>'required|string',//收款账号
            'status' => [
                'required',
                Rule::In([1, 2]),
            ],//收款状态：1-全部 2-部分
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['pay_time'] = strtotime($data['pay_time']);
        $data['created_at'] = time();

        $this->log('采购付款', $data);

        return response()->json(
            MaterielService::payMaterielMoney($data)
        );
    }

    /**
     * @采购单列表
     * created 在 2021/11/25 16:25 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
            'repeal_status'=>'required|integer'//撤销状态：0-未撤销 1-已撤销
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            MaterielService::list(
                    $this->getUserId(),
                    $this->getMainUserId(),
                    $data
                )
        );
    }

    /**
     * @撤销
     * created 在 2021/11/25 17:36 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return response()->json(
            MaterielService::cancel(
                    $this->getMainUserId(),
                    $data
                )
        );
    }

    /**
     * @重新下单
     * created 在 2021/11/26 10:53 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAgain(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['purchase_no'] = SELF::createPurchaseNo();

        return $this->success(
            MaterielService::addAgain(
                    $this->getUserId(),
                    $this->getMainUserId(),
                    $data
                )
        );
    }

    /**
     * @详细
     * created 在 2021/11/26 14:53 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        return $this->success(
            MaterielService::detail(
                    $data
                )
        );
    }

    /**
     * @采购单入库
     * created 在 2021/11/26 14:53 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function materielInStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'status' => [
                'required',
                Rule::In([1, 2]),
            ],//入库状态：1-全部 2-部分
            'in_storage_time' => 'date_format:Y-m-d H:i:s',//入库时间
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(empty($data['content'])) {
            return $this->fail('', '请填写采购内容');
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        $this->log('采购单入库', $data);

        return response()->json(
            MaterielService::materielInStorage(
                    $data
                )
        );
    }

    /**
     * @修改商品采购单价
     * @created 在 2021/12/17 17:21 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author: Sun Wu
     */
    public function editUnitPrice(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//采购单内容id
            'unit_price' => 'required|numeric|min:0'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('修改采购单商品采购单价', $data);
        return response()->json(
            MaterielService::editUnitPrice(
                $data
            )
        );
    }
}
